package com.sc.admin.core.api.web;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sc.admin.core.bo.ResourceBo;
import com.sc.admin.core.service.SysAccountService;
import com.sc.common.annotations.OperationLog;
import com.sc.common.annotations.WebApi;
import com.sc.common.context.DefaultBusinessContext;
import com.sc.common.dto.PageDto;
import com.sc.common.entity.admin.account.SysAccount;
import com.sc.common.entity.admin.account.SysAccountList;
import com.sc.common.entity.admin.account.SysAccountSearch;
import com.sc.common.enums.ApplicationEnum;
import com.sc.common.enums.OperationLogEnum;
import com.sc.common.util.MyStringUtils;
import com.sc.common.util.RC4;
import com.sc.common.util.cache.DataDictionaryUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import com.sc.common.dto.WebResponseDto;

/**
 * @author: wust
 * @date: 2019-12-27 11:55:31
 * @description:
 */
@Api(tags = {"Web接口~账号中心"})
@WebApi
@RequestMapping("/web/v1/AccountController")
@RestController
public class AccountController {
    @Autowired
    private SysAccountService sysAccountServiceImpl;

    @Autowired
    private ResourceBo resourceBo;

    @Autowired
    private Environment environment;

    @ApiOperation(value = "分页查询", httpMethod = "POST")
    @RequestMapping(value = "/listPage", method = RequestMethod.POST)
    public WebResponseDto listPage(@RequestBody SysAccountSearch search) {
        WebResponseDto responseDto = new WebResponseDto();
        DefaultBusinessContext ctx = DefaultBusinessContext.getContext();

        PageDto pageDto = search.getPageDto();
        Page page = PageHelper.startPage(pageDto.getPageNum(),pageDto.getPageSize());
        List<SysAccount> list = sysAccountServiceImpl.select(search);
        if (CollectionUtil.isNotEmpty(list)) {
            List<SysAccountList> accountLists = new ArrayList<>(list.size());
            for (SysAccount account : list) {
                SysAccountList accountList = new SysAccountList();
                BeanUtils.copyProperties(account,accountList);
                accountList.setTypeLabel(DataDictionaryUtil.getLookupNameByCode(ctx.getLocale().toString(), account.getType()));
                accountLists.add(accountList);
            }
            responseDto.setLstDto(accountLists);
        }

        BeanUtils.copyProperties(page,pageDto);
        responseDto.setPage(pageDto);
        return responseDto;
    }


    @ApiOperation(value = "新建账号", httpMethod = "POST", response = WebResponseDto.class)
    @RequestMapping(value = "", method = RequestMethod.POST)
    public WebResponseDto create(@RequestBody SysAccount entity) {
        WebResponseDto responseDto = new WebResponseDto();
        DefaultBusinessContext ctx = DefaultBusinessContext.getContext();

        SysAccount accountSearch = new SysAccount();
        accountSearch.setAccountCode(entity.getAccountCode());
        SysAccount account = sysAccountServiceImpl.selectOne(accountSearch);
        if (account != null) {
            responseDto.setFlag(WebResponseDto.INFO_WARNING);
            responseDto.setMessage("该账号已经存在，不允许重复添加");
            return responseDto;
        }


        String passwordRC4 = "";
        if (MyStringUtils.isNotBlank(MyStringUtils.null2String(entity.getPassword()))) {
            passwordRC4 = RC4.encry_RC4_string(SecureUtil.md5(entity.getPassword()).toUpperCase(), ApplicationEnum.LOGIN_RC4_KEY.getStringValue());
        } else {
            passwordRC4 = RC4.encry_RC4_string(SecureUtil.md5("123456").toUpperCase(), ApplicationEnum.LOGIN_RC4_KEY.getStringValue());
        }
        entity.setPassword(passwordRC4);
        entity.setSource("Web新建");
        entity.setCreaterId(ctx.getAccountId());
        entity.setCreaterName(ctx.getAccountName());
        entity.setCreateTime(new Date());
        sysAccountServiceImpl.insert(entity);
        return responseDto;
    }


    @RequestMapping(value = "", method = RequestMethod.PUT)
    public WebResponseDto update(@RequestBody SysAccount entity) {
        WebResponseDto responseDto = new WebResponseDto();

        if(!"A101702".equals(entity.getType())){
            responseDto.setFlag(WebResponseDto.INFO_WARNING);
            responseDto.setMessage("只能修改普通管理员信息");
            return responseDto;
        }

        sysAccountServiceImpl.updateByPrimaryKeySelective(entity);

        return responseDto;
    }


    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public WebResponseDto delete(@PathVariable Long id) {
        WebResponseDto responseDto = new WebResponseDto();

        SysAccount account = sysAccountServiceImpl.selectByPrimaryKey(id);

        if(!"A101702".equals(account.getType())){
            responseDto.setFlag(WebResponseDto.INFO_WARNING);
            responseDto.setMessage("只能删除普通管理员账号");
            return responseDto;
        }

        sysAccountServiceImpl.deleteByPrimaryKey(id);

        return responseDto;
    }


    @OperationLog(moduleName = OperationLogEnum.MODULE_ADMIN_ACCOUNT, businessName = "重置密码", operationType = OperationLogEnum.Update)
    @RequestMapping(value = "/resetPassword", method = RequestMethod.POST)
    public WebResponseDto resetPassword(@RequestParam Long id) {
        WebResponseDto responseDto = new WebResponseDto();
        DefaultBusinessContext ctx = DefaultBusinessContext.getContext();

        String passwordRC4 = RC4.encry_RC4_string(SecureUtil.md5("123456").toUpperCase(), ApplicationEnum.LOGIN_RC4_KEY.getStringValue());

        SysAccount account = sysAccountServiceImpl.selectByPrimaryKey(id);
        account.setPassword(passwordRC4);
        account.setModifyId(ctx.getAccountId());
        account.setModifyName(ctx.getAccountName());
        account.setModifyTime(new Date());
        sysAccountServiceImpl.updateByPrimaryKeySelective(account);
        return responseDto;
    }


    /**
     * 构建指定账号到资源权限树
     *
     * @param accountId
     * @return
     */
    @RequestMapping(value = "/buildFunctionTreeByAccountId", method = RequestMethod.POST)
    public WebResponseDto buildFunctionTreeByAccountId(@RequestParam("accountId") Long accountId) {
        WebResponseDto responseDto = new WebResponseDto();

        // 只构建普通管理员到资源权限树
        String json = resourceBo.buildFunctionTreeByAccountId("A100401", accountId);
        responseDto.setObj(json);
        return responseDto;
    }


    @OperationLog(moduleName = OperationLogEnum.MODULE_ADMIN_ACCOUNT, businessName = "设置权限", operationType = OperationLogEnum.Update)
    @RequestMapping(value = "/setFunctionPermissions", method = RequestMethod.POST)
    public WebResponseDto setFunctionPermissions(@RequestBody JSONObject jsonObject) {
        WebResponseDto responseDto = sysAccountServiceImpl.setFunctionPermissions(jsonObject);
        return responseDto;
    }
}
